import re
import json
from playwright.sync_api import Playwright, sync_playwright


class OpenFeishuMessage:
    def __init__(self, playwright: Playwright, url, headless: bool = False):
        self.playwright = playwright
        self.headless = headless
        chrome_executable_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
        self.browner = self.playwright.chromium.launch(executable_path=chrome_executable_path,headless=headless)
        self.context = self.browner.new_context()
        self.page = self.context.new_page()
        self.title = self.page.title()
        self.lark_suite_url = url

    def open_browser(self):
        self.page.goto(self.lark_suite_url)
        self.page.wait_for_timeout(1000 * 3)
        video_list = self.page.query_selector_all('a[href^="/video/"]')
        for video in video_list:
            title = str(video.get_property('title'))
            href = str(video.get_property('href'))
            if title and title != '':
                print('[%s](%s)' % (title, href))

    def close(self):
        self.page.close()
        self.context.close()
        self.browner.close()


if __name__ == '__main__':
    while True:
        print('\n选择要执行程序的序号：')
        print(' 1. 输入B站视频链接获取视频标题')
        print(' 2. 退出')
        number = int(input('请输入序号：'))
        if number == 2:
            break
        if number == 1:
            print('请输入B站视频链接：')
            url = str(input())
            print('等待浏览器加载数据3s...\n')
            with sync_playwright() as playwright:
                openFeishuMessage = OpenFeishuMessage(playwright, url=url, headless=True)
                openFeishuMessage.open_browser()
                openFeishuMessage.close()
